package com.poetry.service.impl;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.poetry.constant.RedisConstant;
import com.poetry.domain.po.History;
import com.poetry.domain.po.Poem;
import com.poetry.exception.R;
import com.poetry.mapper.HistoryMapper;
import com.poetry.mapper.PoemMapper;
import com.poetry.service.IHistoryService;
import com.poetry.util.UserContext;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class HistoryServiceImpl extends ServiceImpl<HistoryMapper, History>
        implements IHistoryService {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    @Resource
    private PoemMapper poetryMapper;
    @Override
    @Transactional
    public R<String> addHistory(Integer id) {
        Integer userId = UserContext.getUserId();
        if (userId == null) {return R.error("用户未登录");}
        String listKey = RedisConstant.HISTORY_USER_KEY + userId.toString();
        String setKey = listKey + RedisConstant.HISTORY_SET_KEY;
        Boolean isMember = stringRedisTemplate.opsForSet().isMember(setKey, id.toString());
        History history = new History();
        history.setPoemId(id);
        history.setUserId(userId);
        history.setViewedAt(LocalDateTime.now());
        if (Boolean.TRUE.equals(isMember)) {
            // 浏览记录已存在则更新浏览时间
            this.update(history,
                    new LambdaUpdateWrapper<History>()
                            .eq(History::getUserId, userId)
                            .eq(History::getPoemId, id)
                            .set(History::getViewedAt, LocalDateTime.now()));
            removeRedisFromList(listKey, id);
        } else {
            this.save(history);
            stringRedisTemplate.opsForSet().add(setKey, id.toString());
        }
        stringRedisTemplate.opsForList().leftPush(listKey, JSONUtil.toJsonStr(history));
        stringRedisTemplate.opsForList().trim(listKey, 0, RedisConstant.HISTORY_MAX_SIZE - 1);
        stringRedisTemplate.expire(listKey, RedisConstant.CACHE_HISTORY_TTL, TimeUnit.DAYS);
        stringRedisTemplate.expire(setKey, RedisConstant.CACHE_HISTORY_TTL, TimeUnit.DAYS);
        return R.success(null, "浏览记录添加成功");
    }

    private void removeRedisFromList(String key, Integer poemId) {
        List<String> value = stringRedisTemplate.opsForList().range(key, 0, -1);
        if (value == null || value.isEmpty()) return;
        List<History> list = value.stream().map(s -> JSONUtil.toBean(s, History.class)).toList();
        int index = -1;
        for (int i = 0; i < list.size(); i++) {
            History item = list.get(i);
            if (item.getPoemId().equals(poemId)) {
                index = i;
                break;
            }
        }
        // 删除找到的元素
        if (index >= 0) {
            // 设置占位符并删除
            stringRedisTemplate.opsForList().set(key, index, "TO_DELETE");
            stringRedisTemplate.opsForList().remove(key, 0, "TO_DELETE");
        }
    }

    @Override
    public R<List<History>> queryHistory(Integer limit) {
        Integer userId = UserContext.getUserId();
        if (userId == null) {
            return R.error("用户未登录");
        }
        String listKey = RedisConstant.HISTORY_USER_KEY + userId;
        String setKey = listKey + RedisConstant.HISTORY_SET_KEY;
        List<String> list = stringRedisTemplate.opsForList().range(listKey, 0, limit - 1);
        if (list != null && !list.isEmpty()) {
            List<History> historyList = new java.util.ArrayList<>(list.stream()
                    .map(s -> JSONUtil.toBean(s, History.class))
                    .sorted(Comparator.comparing(History::getPoemId)).toList());
            List<Poem> poems = poetryMapper.selectByIds(historyList.stream().map(History::getPoemId).collect(Collectors.toList()));
            for (int i = 0; i < poems.size(); i++) {
                historyList.get(i).setPoemTitle(poems.get(i).getTitle());
                historyList.get(i).setAuthor(poems.get(i).getAuthor());
                historyList.get(i).setDynasty(poems.get(i).getDynasty());
            }
            historyList.sort(Comparator.comparing(History::getViewedAt).reversed());
            return R.success("查询历史记录成功", historyList);
        }
        List<History> historyList = baseMapper.selectHistoryWithPoemInfo(userId, RedisConstant.HISTORY_MAX_SIZE);
        if (historyList != null && !historyList.isEmpty()) {
            historyList.sort(Comparator.comparing(History::getPoemId));
            stringRedisTemplate.opsForList().leftPushAll(listKey, JSONUtil.toJsonStr(historyList));
            stringRedisTemplate.opsForList().trim(listKey, 0, RedisConstant.HISTORY_MAX_SIZE - 1);
            Set<Integer> poemIds = historyList.stream().map(History::getPoemId).collect(Collectors.toSet());
            if (!poemIds.isEmpty()) {
                stringRedisTemplate.opsForSet().add(setKey, poemIds.toString());
            }
            stringRedisTemplate.expire(listKey, RedisConstant.CACHE_HISTORY_TTL, TimeUnit.DAYS);
            stringRedisTemplate.expire(setKey, RedisConstant.CACHE_HISTORY_TTL, TimeUnit.DAYS);

            List<Poem> poems = poetryMapper.selectByIds(historyList.stream().map(History::getPoemId).collect(Collectors.toList()));

            for (int i = 0; i < poems.size(); i++) {
                historyList.get(i).setPoemTitle(poems.get(i).getTitle());
                historyList.get(i).setAuthor(poems.get(i).getAuthor());
                historyList.get(i).setDynasty(poems.get(i).getDynasty());
            }

            historyList.sort(Comparator.comparing(History::getViewedAt).reversed());
        }
        return R.success("查询浏览记录成功", historyList);
    }

    @Override
    @Transactional
    public R<String> clearHistory() {
        Integer userId = UserContext.getUserId();
        baseMapper.delete(new LambdaQueryWrapper<History>().eq(History::getUserId, userId));
        String listKey = RedisConstant.HISTORY_USER_KEY + userId;
        String setKey = listKey + RedisConstant.HISTORY_SET_KEY;
        stringRedisTemplate.delete(listKey);
        stringRedisTemplate.delete(setKey);
        return R.success(null, "清空浏览记录成功");
    }
}
